package code.oldCode.feishuSpecializedTraining.back_trace;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 26029
 * @date 2025/3/17
 * @description
 */
public class MyBackTrace {
    // 77. 组合
    public List<List<Integer>> combine(int n, int k) {
        List<List<Integer>> lists = new ArrayList<>();
        getCombine(1, n, k, lists, new ArrayList<>());
        return lists;
    }

    public void getCombine(int num, int n, int k, List<List<Integer>> lists, List<Integer> list) {
        if (list.size() == k) {
            lists.add(new ArrayList<>(list));
            return;
        }
        // 剪枝，list中最后一个值到n的数量小于剩余需要的数量的话，说明剩下的已经不够了，return
        if (!list.isEmpty() && n - list.get(list.size() - 1) < k - list.size())
            return;
        for (int i = num; i <= n; i++) {
            list.add(i);
            getCombine(i + 1, n, k, lists, list);
            list.remove(list.size() - 1);
        }
    }

    // 216. 组合总和 III
    public List<List<Integer>> combinationSum3(int k, int n) {
        List<List<Integer>> lists = new ArrayList<>();
        getComSum3(1, 0, k, n, new ArrayList<>(), lists);
        return lists;
    }

    public void getComSum3(int num, int sum, int k, int n, List<Integer> list, List<List<Integer>> lists) {
        if (sum > n)
            return;
        if (list.size() == k && sum == n) {
            lists.add(new ArrayList<>(list));
            return;
        }
        for (int i = num; i <= 9; i++) {
            list.add(i);
            getComSum3(i + 1, sum + i, k, n, list, lists);
            list.remove(list.size() - 1);
        }
    }

    // 17. 电话号码的字母组合
    public List<String> letterCombinations(String digits) {
        List<String> stringList = new ArrayList<>();
        if (digits.isEmpty())
            return stringList;
        Map<Character, char[]> map = new HashMap<>();
        map.put('2', new char[]{'a', 'b', 'c'});
        map.put('3', new char[]{'d', 'e', 'f'});
        map.put('4', new char[]{'g', 'h', 'i'});
        map.put('5', new char[]{'j', 'k', 'l'});
        map.put('6', new char[]{'m', 'n', 'o'});
        map.put('7', new char[]{'p', 'q', 'r', 's'});
        map.put('8', new char[]{'t', 'u', 'v'});
        map.put('9', new char[]{'w', 'x', 'y', 'z'});
        getLetterCombine(0, digits, new StringBuilder(), map, stringList);
        return stringList;
    }

    public void getLetterCombine(int pos, String digits, StringBuilder sb, Map<Character, char[]> map, List<String > stringList) {
        if (pos == digits.length()) {
            stringList.add(sb.toString());
            return;
        }
        char[] nowChars = map.get(digits.charAt(pos));
        for (char nowChar : nowChars) {
            sb.append(nowChar);
            getLetterCombine(pos + 1, digits, sb, map, stringList);
            sb.deleteCharAt(sb.length() - 1);
        }
    }
}
